package com.xiaozhengkeji.colastartboot.api;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.xiaozhengkeji.colastartboot.annotation.IPFlowValve;
import com.xiaozhengkeji.colastartboot.base.entitys.SystemUser;
import com.xiaozhengkeji.colastartboot.base.redis.VerifyBaseRedis;
import com.xiaozhengkeji.colastartboot.base.services.SystemUserService;
import com.xiaozhengkeji.colastartboot.bean.ResponseBean;
import com.xiaozhengkeji.colastartboot.bean.type.ResCodeType;
import com.xiaozhengkeji.colastartboot.services.SystemUserUtilsService;
import com.xiaozhengkeji.colastartboot.utils.page.ListPager;
import com.xiaozhengkeji.colastartboot.utils.page.Pagers;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;

/**
 * 系统用户Api
 */
@Slf4j
@RestController
@RequestMapping("/web/system/user")
public class UserApi {

    SystemUserService systemUserService;
    SystemUserUtilsService systemUserUtilsService;
    VerifyBaseRedis verifyBaseRedis;


    @Autowired
    public UserApi(SystemUserService systemUserService,
                   SystemUserUtilsService systemUserUtilsService,
                   VerifyBaseRedis verifyBaseRedis) {
        this.systemUserService = systemUserService;
        this.systemUserUtilsService = systemUserUtilsService;
        this.verifyBaseRedis = verifyBaseRedis;
    }

    /**
     * 登录账户
     */
    @ApiOperation("登录系统用户")
    @PostMapping("/login")
    @IPFlowValve(urlLogo = "userLogin", limit = 10, time = 60, message = "请勿非法破解用户系统")
    public ResponseBean login(@ApiParam("用户名") @RequestParam("username") String username,
                              @ApiParam("密码") @RequestParam("password") String password,
                              @ApiParam("获取图片验证码时提交的时间戳") @RequestParam("verificationCodeTag") String verificationCodeTag,
                              @ApiParam("图片验证码的验证码") @RequestParam("verificationCode") String verificationCode, HttpServletRequest request) {
        String redis_gcv = verifyBaseRedis.getVerificationCode(verificationCodeTag);
        if (redis_gcv == null) {
            return new ResponseBean(ResCodeType.Error, "验证码过期!", null, 3);
        }
        if (!redis_gcv.equalsIgnoreCase(verificationCode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 2);
        }
        verifyBaseRedis.delVerificationCode(verificationCodeTag);
        List<SystemUser> user_entity_Base = systemUserService.queryByUsername(username);
        if (user_entity_Base.isEmpty()) {
            return new ResponseBean(ResCodeType.Error, "无此用户!", null, 4);
        }
        if (!user_entity_Base.get(0).getPassword().equals(password)) {
            return new ResponseBean(ResCodeType.Error, "用户密码错误!", null, null);
        }
        StpUtil.login(user_entity_Base.get(0).getUid(), "webapp");
        List<String> permission = JSON.parseArray(user_entity_Base.get(0).getUserRole(), String.class);
        return new ResponseBean(ResCodeType.Success, "登录成功", StpUtil.getTokenInfo(), permission);
    }

    /**
     * 注册用户
     */
    @ApiOperation("注册用户")
    @PostMapping("/register")
    @IPFlowValve(urlLogo = "register", limit = 2, time = 60, message = "请勿非法破解用户系统")
    public ResponseBean register(@ApiParam("邮箱") @RequestParam("email") String email,
                                 @ApiParam("用户名") @RequestParam("username") String username,
                                 @ApiParam("密码") @RequestParam("password") String password,
                                 @ApiParam("获取图片验证码时提交的时间戳") @RequestParam("verificationCodeTag") String verificationCodeTag,
                                 @ApiParam("图片验证码的验证码") @RequestParam("verificationCode") String verificationCode, HttpServletRequest request) {
        String redis_gcv = verifyBaseRedis.getVerificationCode(verificationCodeTag);
        if (redis_gcv == null) {
            return new ResponseBean(ResCodeType.Error, "验证码过期!", null, 3);
        }
        if (!redis_gcv.equalsIgnoreCase(verificationCode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 2);
        }
        verifyBaseRedis.delVerificationCode(verificationCodeTag);
        if (systemUserUtilsService.registerSystemUser(username, password, email, "请设置备注!")) {
            return new ResponseBean(ResCodeType.Success, "注册完成!", null, null);
        }
        return new ResponseBean(ResCodeType.Error, "注册失败!存在相同用户名!或者数据库连接失败!", null, null);


    }

    /**
     * 添加一个系统用户
     */
    @ApiOperation("添加一个用户")
    @PostMapping("/createSystemUser")
    @SaCheckPermission("user:admin")
    public ResponseBean createSystemUser(@ApiParam("用户名") @RequestParam("username") String username,
                                         @ApiParam("密码") @RequestParam("password") String password,
                                         @ApiParam("邮箱") @RequestParam("email") String email) {
        if (systemUserUtilsService.registerSystemUser(username, password, email, "请设置备注!")) {
            return new ResponseBean(ResCodeType.Success, "创建系统用户完成!", null, null);
        }
        return new ResponseBean(ResCodeType.Error, "创建失败!存在相同用户名!或者数据库连接失败!", null, null);
    }


    /**
     * 设置一个账户的状态
     */
    @ApiOperation("设置一个账户的状态")
    @PostMapping("/setUserState")
    @SaCheckPermission("user:admin")
    public ResponseBean setUserState(@ApiParam("索引") @RequestParam("uid") Integer uid,
                                     @ApiParam("用户状态 1=正常 -1=封禁 -2=冻结") @RequestParam("state") Integer state) {
        if (systemUserUtilsService.setUserState(uid, state)) {
            return new ResponseBean(ResCodeType.Success, "设置成功!", null, null);
        }
        return new ResponseBean(ResCodeType.Error, "无法设置用户状态!数据库未响应", null, null);
    }

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @PostMapping("/systemUserAllTable")
    @SaCheckPermission("user:admin")
    public ResponseBean systemUserAllTable(@ApiParam("需要查询用户名 空为查询全部") @RequestParam("query") String query,
                                           @ApiParam("第几页") @RequestParam("pageNum") Integer pageNum,
                                           @ApiParam("每页数量") @RequestParam("pageSize") Integer pageSize) {
        //更新模糊查询
        List<SystemUser> systemUserList = systemUserService.queryByUsernameLike(query);
        ListPager<SystemUser> userEntityListPager = Pagers.newListPager(pageSize, systemUserList);
        List<SystemUser> userPager = new LinkedList<>();
        for (SystemUser temp_user : userEntityListPager.getPage(pageNum)) {
            temp_user.setPassword("NOT Access");
            userPager.add(temp_user);
        }
        return new ResponseBean(ResCodeType.Success, "!", userPager, systemUserList.size());
    }


    @ApiOperation("验证Token的有效性")
    @GetMapping("/verifyToken")
    @IPFlowValve(urlLogo = "verifyToken", limit = 5, time = 60, message = "请勿短时间内连续验证")
    public ResponseBean verifyToken(@RequestParam("Token") String Token) {
        if (StpUtil.getLoginIdByToken(Token) == null) {
            return new ResponseBean(ResCodeType.Error, "Token过期!", null, null);
        }
        Integer loginID = Integer.parseInt((String) StpUtil.getLoginIdByToken(Token));
        SystemUser userEntity = systemUserService.selectByPrimaryKey(loginID);
        List<String> permission = JSON.parseArray(userEntity.getUserRole(), String.class);
        return new ResponseBean(ResCodeType.Success, "自动登录成功!", userEntity.getUsername(), permission);
    }

    @ApiOperation("获取用户的详情")
    @GetMapping("/info")
    @SaCheckPermission("user:admin")
    public ResponseBean getUserInfo(@RequestParam("uid") Integer uid) {
        return new ResponseBean(ResCodeType.Success, "获取完成!", systemUserService.selectByPrimaryKey(uid), null);
    }
}
